#!/usr/bin/env python
# -*- coding: UTF-8 -*-

try:
	import emblem
	import sys
	import pygame
	from animatable import Animatable
	from pygame.locals import *
	from utils import *
except ImportError, err:
	print "Could not load %s module." % (err)
	sys.exit(2)

# a few constants
CURSOR_ZERO = 40
FLD_TILE_SZ = 48
CURSOR_RECT = (64, 64)
TILE_SZ = 32
EMBLEM_RECT = (16, 16)

'''
Cursor

This is the squarish thing that a user moves and issues commands with.

Note: Tile size is 48. In order to encompass a tile, the Cursor is
8px larger on each side, so its total length is 64. In the creature and
battlefield modules calculations are based on 48. In here we have to
always consider this offset.
'''

class Cursor(pygame.sprite.Sprite, Animatable):
	def __init__(self, layer):
		pygame.sprite.Sprite.__init__(self)
		Animatable.__init__(self)
		self.set_anim_params(FLD_TILE_SZ)
		self.rect = pygame.rect.Rect((0, 0), CURSOR_RECT)
		self.image = pygame.Surface(self.rect.size).convert()

		# cursor at "0,0" is actually "40,40"
		self.x = CURSOR_ZERO
		self.y = CURSOR_ZERO
		# starting cursor position "12,0"
		self.x += (12 * FLD_TILE_SZ)
		self.y += (0 * FLD_TILE_SZ)
		self.emblem = emblem.Emblem()
		#self.emblem.set_action(emblem.DEF_MAGIC)

		screen_rect = pygame.display.get_surface().get_rect()
		# top & left gutters are always 48 px.
		right_gutter = screen_rect.width % 48 or 48
		bottom_gutter = screen_rect.height % 48 or 48
		# cursor_max = full length - cursor offset - field tile size - gutter
		self.max_x = screen_rect.width - 8 - FLD_TILE_SZ - right_gutter
		self.max_y = screen_rect.height - 8 - FLD_TILE_SZ - bottom_gutter

		self.tile = emblem.get_cursor_tile()

		colorkey = self.tile.get_at((0, 0))
		self.image.set_colorkey(colorkey, RLEACCEL)
		self.blank = pygame.Surface((TILE_SZ, TILE_SZ)).convert()
		self.blank.fill(colorkey)

		self.blit_tiles()

		self.layer = layer
		self.show()

	def blit_tiles(self):
		self.image.blit(self.tile, ((0,0)))
		self.tile = pygame.transform.flip(self.tile, 1, 0)
		self.image.blit(self.tile, ((TILE_SZ, 0)))
		self.tile = pygame.transform.flip(self.tile, 0, 1)
		self.image.blit(self.tile, ((TILE_SZ, TILE_SZ)))
		self.tile = pygame.transform.flip(self.tile, 1, 0)
		self.image.blit(self.tile, ((0, TILE_SZ)))
		#self.tile = pygame.transform.flip(self.tile, 0, 1)


	def update(self):
		if self.moving:
			self.slide()
		self.rect.topleft = (self.x, self.y)
		if self.emblem.update():
			self.image.blit(self.blank, (EMBLEM_RECT))
			self.image.blit(self.emblem.image, (EMBLEM_RECT))

	def move(self, key):
		if (key == K_UP and self.y > CURSOR_ZERO) \
		or (key == K_RIGHT and self.x < self.max_x) \
		or (key == K_DOWN and self.y < self.max_y) \
		or (key == K_LEFT and self.x > CURSOR_ZERO):
			self.moving = key
			return key
		else:
			return 0

	def do_action(self):
		pass

	def hide(self):
		self.layer.remove(self)

	def show(self):
		self.layer.add(self)
